using System;
using System.Drawing;
using System.Runtime.InteropServices;

namespace Linquid
{
	/// <summary>
	/// Provides platform-independant access to the font properties
	/// </summary>
	public static class FontUtils
	{
		/// <summary>
		/// Gets the height of the font.
		/// </summary>
		/// <param name="font">Font to get the height from.</param>
		/// <returns>Height of the font.</returns>
		public static float GetHeight(this Font font)
		{			
			return font.Size / 72 * getDPI();
		}

		private static Func<float> getDPI = () =>
		{
			if (Environment.OSVersion.Platform == PlatformID.WinCE)
			{
			 	getDPI = GetDPICF;
			}
			else
			{
				getDPI = GetDPI;
			}
				
			return getDPI();
		};
		
		private static float GetDPI()
		{			
			var ptr = GetDC(IntPtr.Zero);
			var res = 0.0f;
			using (var graphics = Graphics.FromHdc(ptr))
			{
				res = graphics.DpiY;
			}
			ReleaseDC(IntPtr.Zero, ptr);
			return res;		
		}				

		private static float GetDPICF()
		{			
			var ptr = GetDCCF(IntPtr.Zero);
			var res = 0.0f;
			using (var graphics = Graphics.FromHdc(ptr))
			{
				res = graphics.DpiY;
			}
			ReleaseDCCF(IntPtr.Zero, ptr);
			return res;		
		}
		
		[DllImport("user32.dll", EntryPoint="GetDC")]
    	 private extern static IntPtr GetDC(IntPtr hwnd);
	    
     	 [DllImport("user32.dll", EntryPoint="ReleaseDC")]
    	 private extern static int ReleaseDC(IntPtr hwnd, IntPtr hdc);
		
		[DllImport("coredll.dll", EntryPoint="GetDC")]
    	 private extern static IntPtr GetDCCF(IntPtr hwnd);
	    
     	 [DllImport("coredll.dll", EntryPoint="ReleaseDC")]
    	 private extern static int ReleaseDCCF(IntPtr hwnd, IntPtr hdc);
	}
}